const db = uniCloud.database()
let userCollectionName = 'uni-id-users'
let userCollection = db.collection(userCollectionName)
let verifyCollectionName = 'opendb-verify-codes'
let verifyCollection = db.collection(verifyCollectionName)
let roleCollectionName = 'uni-id-roles'
let roleCollection = db.collection(roleCollectionName)
let permissionCollectionName = 'uni-id-permissions'
let permissionCollection = db.collection(permissionCollectionName)

// 设置默认微信保存openid的名称
let wxOpenIdName = ''

// 设置数据库名称
const setCollectionName = (collectionNameObj) => {
  wxOpenIdName = collectionNameObj['wx-openid-name'] || ''

  userCollectionName = collectionNameObj['uni-id-users']
  userCollection = db.collection(userCollectionName)

  verifyCollectionName = collectionNameObj['opendb-verify-codes']
  verifyCollection = db.collection(verifyCollectionName)

  roleCollectionName = collectionNameObj['uni-id-roles']
  roleCollection = db.collection(roleCollectionName)

  permissionCollectionName = collectionNameObj['uni-id-permissions']
  permissionCollection = db.collection(permissionCollectionName)
}

// 单端用户唯一字段，注意有些字段是对象类型
// 返回国际化的key
const uniqueUserParam = {
  username: 'username',
  mobile: 'mobile',
  email: 'email',
  wx_unionid: 'wechat-account',
  'wx_openid.app-plus': 'wechat-account',
  'wx_openid.app': 'wechat-account',
  'wx_openid.mp-weixin': 'wechat-account',
  qq_unionid: 'qq-account',
  'qq_openid.app-plus': 'qq-account',
  'qq_openid.app': 'qq-account',
  'qq_openid.mp-weixin': 'qq-account',
  ali_openid: 'alipay-account',
  apple_openid: 'alipay-account'
}
// 公用错误码
const PublicErrorCode = {
  DB_ERROR: 90001,
  PARAM_REQUIRED: 90002,
  PARAM_ERROR: 90003,
  USER_NOT_EXIST: 90004,
  ROLE_NOT_EXIST: 90005,
  PERMISSION_NOT_EXIST: 90006
}

const UserStatus = {
  normal: 0,
  banned: 1,
  audit: 2,
  auditFailed: 3,
  closed: 4
}

export {
  db,
  PublicErrorCode,
  userCollection,
  verifyCollection,
  roleCollection,
  permissionCollection,
  userCollectionName,
  verifyCollectionName,
  roleCollectionName,
  permissionCollectionName,
  uniqueUserParam,
  UserStatus,
  setCollectionName,
  wxOpenIdName
}
